import importlib
import os
from pathlib import Path

from fastapi import APIRouter
from fastapi.routing import APIWebSocketRoute
from init.app_init import create_app

app = create_app()
base_dir = './app_function/'
service_dir = []
interface_list = []
eb_interface_list = ["my_apps"]


def get_all_subdirectories(base_path, prefix):
    sub_dirs = []
    base_path = Path(base_path)
    for entry in base_path.iterdir():
        if entry.is_dir() and not entry.name.endswith("__pycache__"):
            sub_dirs.extend(get_all_subdirectories(entry, prefix / entry.name))
            sub_dirs.append(str(prefix / entry.name))
    return sub_dirs


for valid_interface_dir in interface_list:
    service_dir.append(valid_interface_dir)
    service_dir.extend(get_all_subdirectories(f"{base_dir}{valid_interface_dir}", Path(valid_interface_dir)))

service_dir.extend(get_all_subdirectories(f"{base_dir}{eb_interface_list[0]}", Path(eb_interface_list[0])))

visited_routes = set()
for ser in service_dir:
    try:
        func_dir = os.listdir(f'{base_dir}{ser}')
        for interface_file in func_dir:
            if interface_file.startswith('interface'):
                import_package = f'.{ser.replace(os.sep, ".")}.{interface_file.split(".")[0]}'
                params_ = importlib.import_module(import_package, package='app_function')
                routes_module = getattr(params_, 'router')

                http_routes = []
                ws_routes = []
                for route in routes_module.routes:
                    if isinstance(route, APIWebSocketRoute):
                        ws_routes.append(route)
                        continue
                    operation_id = f"{route.path}_{route.name}_{'_'.join(route.methods)}"
                    if operation_id not in visited_routes:
                        http_routes.append(route)
                        visited_routes.add(operation_id)
                if ws_routes:
                    ws_router = APIRouter()
                    ws_router.routes = ws_routes
                    app.include_router(ws_router)
                if http_routes:
                    routes_module.routes = http_routes
                    prefix = "/v1" if any(
                        ser.startswith(pf) for pf in eb_interface_list) else f"/{ser.replace(os.sep, '/')}"
                    app.include_router(router=routes_module, prefix=prefix)
    except NotADirectoryError:
        continue
